<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="一切先从核心玩法开始 如何运动 控制蛇头的方向   游戏界面 绘制游戏内容 让一切都动起来 获取键盘事件   游戏功能实现 穿墙效果 蛇的身子变长（重点） 碰撞检测 检测吃食物 计分系统     一切先从核心玩法开始首先贪吃蛇的运动是发生在一个规范的矩阵中，而矩阵中的每一方格就是蛇的身子，而蛇的运动就是一次一次更新正方形的位置，然后通过panel绘制上去所以我们使用两个数组来储存贪吃蛇的位置">
<meta property="og:type" content="article">
<meta property="og:title" content="Java贪吃蛇开发">
<meta property="og:url" content="http://yoursite.com/2020/03/04/Java%E8%B4%AA%E5%90%83%E8%9B%87%E5%BC%80%E5%8F%91/index.html">
<meta property="og:site_name" content="Roderick&#39;s blog">
<meta property="og:description" content="一切先从核心玩法开始 如何运动 控制蛇头的方向   游戏界面 绘制游戏内容 让一切都动起来 获取键盘事件   游戏功能实现 穿墙效果 蛇的身子变长（重点） 碰撞检测 检测吃食物 计分系统     一切先从核心玩法开始首先贪吃蛇的运动是发生在一个规范的矩阵中，而矩阵中的每一方格就是蛇的身子，而蛇的运动就是一次一次更新正方形的位置，然后通过panel绘制上去所以我们使用两个数组来储存贪吃蛇的位置">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-04T14:51:05.334Z">
<meta property="article:modified_time" content="2020-02-16T14:01:36.554Z">
<meta property="article:author" content="Roderick Xiang">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2020/03/04/Java%E8%B4%AA%E5%90%83%E8%9B%87%E5%BC%80%E5%8F%91/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>Java贪吃蛇开发 | Roderick's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Roderick's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/03/04/Java%E8%B4%AA%E5%90%83%E8%9B%87%E5%BC%80%E5%8F%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Roderick Xiang">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Roderick's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java贪吃蛇开发
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-04 22:51:05" itemprop="dateCreated datePublished" datetime="2020-03-04T22:51:05+08:00">2020-03-04</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-02-16 22:01:36" itemprop="dateModified" datetime="2020-02-16T22:01:36+08:00">2020-02-16</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <!-- TOC -->

<ul>
<li><a href="#一切先从核心玩法开始">一切先从核心玩法开始</a><ul>
<li><a href="#如何运动">如何运动</a></li>
<li><a href="#控制蛇头的方向">控制蛇头的方向</a></li>
</ul>
</li>
<li><a href="#游戏界面">游戏界面</a><ul>
<li><a href="#绘制游戏内容">绘制游戏内容</a></li>
<li><a href="#让一切都动起来">让一切都动起来</a></li>
<li><a href="#获取键盘事件">获取键盘事件</a></li>
</ul>
</li>
<li><a href="#游戏功能实现">游戏功能实现</a><ul>
<li><a href="#穿墙效果">穿墙效果</a></li>
<li><a href="#蛇的身子变长重点">蛇的身子变长（重点）</a></li>
<li><a href="#碰撞检测">碰撞检测</a></li>
<li><a href="#检测吃食物">检测吃食物</a></li>
<li><a href="#计分系统">计分系统</a></li>
</ul>
</li>
</ul>
<!-- /TOC -->
<h3 id="一切先从核心玩法开始"><a href="#一切先从核心玩法开始" class="headerlink" title="一切先从核心玩法开始"></a>一切先从核心玩法开始</h3><p>首先贪吃蛇的运动是发生在一个规范的矩阵中，而矩阵中的每一方格就是蛇的身子，而蛇的运动就是一次一次更新正方形的位置，然后通过panel绘制上去<br><br>所以我们使用两个数组来储存贪吃蛇的位置,snakeX用来储存横坐标，而snakeY用来储存纵坐标的位置<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//贪吃蛇初始的位置（一个头，两个身子）</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">Snake</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        snakeX[<span class="number">0</span>] = <span class="number">400</span>;</span><br><span class="line">        snakeY[<span class="number">0</span>] = <span class="number">400</span>;</span><br><span class="line">        snakeX[<span class="number">1</span>] = <span class="number">380</span>;</span><br><span class="line">        snakeY[<span class="number">1</span>] = <span class="number">400</span>;</span><br><span class="line">        snakeX[<span class="number">2</span>] = <span class="number">360</span>;</span><br><span class="line">        snakeY[<span class="number">2</span>] = <span class="number">400</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h4 id="如何运动"><a href="#如何运动" class="headerlink" title="如何运动"></a>如何运动</h4><p>我们只要更新蛇的位置就能让它动起来了，所以我们定义两个速度”speedX”和”speedY”用来控制头的位置<br><br>只动了头并没有用，还有身子，我们只需要用从尾巴开始使用循环继承上一个身体的位置，知道继承头部位置<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">move</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//身体跟着头走</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = length - <span class="number">1</span>; i &gt; <span class="number">0</span>; i--) &#123;</span><br><span class="line">        snakeX[i] = snakeX[i - <span class="number">1</span>];</span><br><span class="line">        snakeY[i] = snakeY[i - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    snakeX[<span class="number">0</span>] += speedX;</span><br><span class="line">    snakeY[<span class="number">0</span>] += speedY;</span><br><span class="line">    isTmpMove = <span class="keyword">true</span>;</span><br><span class="line">    checkBoundaries();</span><br><span class="line">    System.out.format(<span class="string">"%d %d\n"</span>, snakeX[<span class="number">0</span>], snakeY[<span class="number">0</span>]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="控制蛇头的方向"><a href="#控制蛇头的方向" class="headerlink" title="控制蛇头的方向"></a>控制蛇头的方向</h4><p>为了跟好的控制小蛇，直接控制蛇头来的最为直接。但是这里有一个会产生BUG的点，蛇头不能做反方向运动，所以我们还要给蛇头添加一个方向”direction”属性，只有当按键按下和方向条件满足时才能改变蛇头的运动方向<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">changeDirection</span><span class="params">(KeyEvent e)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (e.getKeyCode() == KeyEvent.VK_UP &amp;&amp; !direction.equals(<span class="string">"down"</span>)) &#123;</span><br><span class="line">        direction = <span class="string">"up"</span>;</span><br><span class="line">        speedX = <span class="number">0</span>;</span><br><span class="line">        speedY = -<span class="number">20</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e.getKeyCode() == KeyEvent.VK_DOWN &amp;&amp; !direction.equals(<span class="string">"UP"</span>)) &#123;</span><br><span class="line">        direction = <span class="string">"down"</span>;</span><br><span class="line">        speedX = <span class="number">0</span>;</span><br><span class="line">        speedY = <span class="number">20</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e.getKeyCode() == KeyEvent.VK_RIGHT &amp;&amp; !direction.equals(<span class="string">"left"</span>)) &#123;</span><br><span class="line">        direction = <span class="string">"right"</span>;</span><br><span class="line">        speedX = <span class="number">20</span>;</span><br><span class="line">        speedY = <span class="number">0</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e.getKeyCode() == KeyEvent.VK_LEFT &amp;&amp; !direction.equals(<span class="string">"right"</span>)) &#123;</span><br><span class="line">        direction = <span class="string">"left"</span>;</span><br><span class="line">        speedX = -<span class="number">20</span>;</span><br><span class="line">        speedY = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    isTmpMove = <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="游戏界面"><a href="#游戏界面" class="headerlink" title="游戏界面"></a>游戏界面</h3><p>游戏界面我们使用Jframe来实现（我好方便实现关闭功能）<br><br>写一个类类继承Jframe，在里面添加面板并且进行初始化设置<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyFrame</span> <span class="keyword">extends</span> <span class="title">JFrame</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        JFrame frame = <span class="keyword">new</span> JFrame();</span><br><span class="line">        setTitle(<span class="string">"贪吃蛇"</span>);</span><br><span class="line">        setResizable(<span class="keyword">false</span>);</span><br><span class="line">        setBounds(<span class="number">300</span>,<span class="number">100</span>,<span class="number">865</span>,<span class="number">830</span>); <span class="comment">//840 *780 （界面的大小一定要设置正确）</span></span><br><span class="line">        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//添加Panel</span></span><br><span class="line">        GamePanel panel = <span class="keyword">new</span> GamePanel();</span><br><span class="line">        add(panel);</span><br><span class="line">        setVisible(<span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="绘制游戏内容"><a href="#绘制游戏内容" class="headerlink" title="绘制游戏内容"></a>绘制游戏内容</h4><p>已经添加了JPanal（GamePanel）,所以到Jpanal中添加游戏中需要绘制的内容<br><br>在Jpanal中重写paintComponent就能在实例化Jpanal时使用画笔绘制图像（方法自行被调用），这个类也是作为游戏的主类<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPaint</span> <span class="keyword">extends</span> <span class="title">JPanel</span> </span>&#123;&#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">paintComponent</span><span class="params">(Graphics g)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.paintComponent(g);    <span class="comment">//清屏</span></span><br><span class="line">        g.setColor(Color.BLACK);</span><br><span class="line">        g.fillRect(<span class="number">100</span>,<span class="number">100</span>,<span class="number">100</span>,<span class="number">100</span>);</span><br><span class="line">        <span class="comment">//绘制所有的功能，省略不写......</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以有这个就能画小蛇了！<br></p>
<h4 id="让一切都动起来"><a href="#让一切都动起来" class="headerlink" title="让一切都动起来"></a>让一切都动起来</h4><p>为了有运动的效果，我们使用循环实现，这里我们使用ActionListener（函数式接口）用作定时器，我们实现一下接口里面的actionPerformed方法在方法里写需要定时执行的事件。定时器使用timer.start()开启<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//执行定时操作</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">actionPerformed</span><span class="params">(ActionEvent e)</span> </span>&#123;</span><br><span class="line">    snake.move();</span><br><span class="line">    snake.checkEatFood(food);</span><br><span class="line">    food.changeFoodPosition();  <span class="comment">//更改食物的位置</span></span><br><span class="line">    snake.checkCollide();   <span class="comment">//碰撞检测</span></span><br><span class="line">    repaint();  <span class="comment">//重新绘制图像</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="获取键盘事件"><a href="#获取键盘事件" class="headerlink" title="获取键盘事件"></a>获取键盘事件</h4><p>实现KeyListener接口来进行事件监听<br><br>使用之间还要设置监听<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">JPanal.setFocusable(<span class="keyword">true</span>); <span class="comment">//设置监听焦点</span></span><br><span class="line">Jpanal.addKeyListener(<span class="keyword">this</span>);   <span class="comment">//添加键盘监听事件</span></span><br><span class="line">接口中有三个抽象方法&lt;br&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">keyPressed</span><span class="params">(KeyEvent e)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> keycode = e.getKeyCode();</span><br><span class="line">    <span class="keyword">if</span> (keycode == KeyEvent.VK_SPACE) &#123;</span><br><span class="line">        isStart = !isStart;</span><br><span class="line">        <span class="keyword">if</span> (isStart) &#123;</span><br><span class="line">            timer.start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (snake.isTmpMove) &#123;   <span class="comment">//判断小蛇是否移动，避免蛇头折回</span></span><br><span class="line">        snake.changeDirection(e);</span><br><span class="line">    &#125;</span><br><span class="line">    repaint();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="游戏功能实现"><a href="#游戏功能实现" class="headerlink" title="游戏功能实现"></a>游戏功能实现</h3><h4 id="穿墙效果"><a href="#穿墙效果" class="headerlink" title="穿墙效果"></a>穿墙效果</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkBoundaries</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (snakeX[<span class="number">0</span>] &gt; <span class="number">840</span>) &#123;</span><br><span class="line">        snakeX[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (snakeX[<span class="number">0</span>] &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        snakeX[<span class="number">0</span>] = <span class="number">840</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (snakeY[<span class="number">0</span>] &gt; <span class="number">780</span>) &#123;</span><br><span class="line">        snakeY[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (snakeY[<span class="number">0</span>] &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        snakeY[<span class="number">0</span>] = <span class="number">780</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="蛇的身子变长（重点）"><a href="#蛇的身子变长（重点）" class="headerlink" title="蛇的身子变长（重点）"></a>蛇的身子变长（重点）</h4><p>我们让小蛇的尾部变长而不是头部，所以要参考蛇身最后的参数，并且获取速度<br><br>速度使用前坐标减后左边产生的差值得到<br><br>增加的位置通过蛇尾减速度得到<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getLonger</span><span class="params">(Food food)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (food.isEat) &#123;</span><br><span class="line">        Point.getNormalFoodPoint();</span><br><span class="line">        snakeX[length] = snakeX[length - <span class="number">1</span>] - (snakeX[length - <span class="number">2</span>] - snakeX[length - <span class="number">1</span>]);</span><br><span class="line">        snakeY[length] = snakeY[length - <span class="number">1</span>] - (snakeY[length - <span class="number">2</span>] - snakeY[length - <span class="number">1</span>]);</span><br><span class="line">        length++;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (food.isBonusEat) &#123;</span><br><span class="line">        Point.getBonusFoodPoint();</span><br><span class="line">        snakeX[length] = snakeX[length - <span class="number">1</span>] - (snakeX[length - <span class="number">2</span>] - snakeX[length - <span class="number">1</span>]);</span><br><span class="line">        snakeY[length] = snakeY[length - <span class="number">1</span>] - (snakeY[length - <span class="number">2</span>] - snakeY[length - <span class="number">1</span>]);</span><br><span class="line">        length++;</span><br><span class="line">        food.isBonusEat = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="碰撞检测"><a href="#碰撞检测" class="headerlink" title="碰撞检测"></a>碰撞检测</h4><p>遍历除了蛇头以外的位置,当坐标有相同的时候停止游戏<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkCollide</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (snakeX[i] == snakeX[<span class="number">0</span>] &amp;&amp; snakeY[i] == snakeY[<span class="number">0</span>]) &#123;</span><br><span class="line">            GamePanel.isDead = <span class="keyword">true</span>;</span><br><span class="line">            System.out.format(<span class="string">"%d %d %d %d\n"</span>, snakeX[i], snakeY[i], snakeX[<span class="number">0</span>], snakeY[<span class="number">0</span>]);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="检测吃食物"><a href="#检测吃食物" class="headerlink" title="检测吃食物"></a>检测吃食物</h4><p>判断头部位置是否与食物重叠就行<br><br>特殊食物还需要判断下是否存在<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkEatFood</span><span class="params">(Food food)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (snakeX[<span class="number">0</span>] == food.normalX &amp;&amp; snakeY[<span class="number">0</span>] == food.normalY) &#123;</span><br><span class="line">        food.isEat = <span class="keyword">true</span>;</span><br><span class="line">        getLonger(food);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (snakeX[<span class="number">0</span>] == food.bonusX &amp;&amp; snakeY[<span class="number">0</span>] == food.bonusY &amp;&amp; food.hasBonus) &#123;</span><br><span class="line">        food.isBonusEat = <span class="keyword">true</span>;</span><br><span class="line">        food.hasBonus = <span class="keyword">false</span>;</span><br><span class="line">        getLonger(food);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="计分系统"><a href="#计分系统" class="headerlink" title="计分系统"></a>计分系统</h4><p>使用BufferReader和BufferWriter读写记录，获取最高分<br></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">writeResult</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    BufferedWriter bw = <span class="keyword">new</span> BufferedWriter(<span class="keyword">new</span> FileWriter(<span class="string">"记录.txt"</span>, <span class="keyword">true</span>));</span><br><span class="line">    bw.write(<span class="string">"player"</span> + <span class="string">"\t"</span> + point);</span><br><span class="line">    bw.newLine();</span><br><span class="line">    bw.close();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">readBestResult</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    BufferedReader br = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> FileReader(<span class="string">"记录.txt"</span>));</span><br><span class="line">    String line;</span><br><span class="line">    <span class="keyword">int</span> score;</span><br><span class="line">    <span class="keyword">while</span> ((line = br.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        String[] tmp = line.split(<span class="string">"\t"</span>);</span><br><span class="line">        score = Integer.parseInt(tmp[<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">if</span> (score &gt; bestScore) &#123;</span><br><span class="line">            bestScore = score;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/02/13/%E5%9C%A8%E8%A5%BF%E9%83%A8%E7%9A%84%E9%82%A3%E4%BA%9B%E6%97%A5%E5%AD%90/" rel="prev" title="在西部的那些日子">
      <i class="fa fa-chevron-left"></i> 在西部的那些日子
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/04/%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0%E9%A1%B5%E9%9D%A2%E7%99%BB%E5%85%A5/" rel="next" title="简单实现页面登入">
      简单实现页面登入 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一切先从核心玩法开始"><span class="nav-number">1.</span> <span class="nav-text">一切先从核心玩法开始</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#如何运动"><span class="nav-number">1.1.</span> <span class="nav-text">如何运动</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#控制蛇头的方向"><span class="nav-number">1.2.</span> <span class="nav-text">控制蛇头的方向</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#游戏界面"><span class="nav-number">2.</span> <span class="nav-text">游戏界面</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#绘制游戏内容"><span class="nav-number">2.1.</span> <span class="nav-text">绘制游戏内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#让一切都动起来"><span class="nav-number">2.2.</span> <span class="nav-text">让一切都动起来</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取键盘事件"><span class="nav-number">2.3.</span> <span class="nav-text">获取键盘事件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#游戏功能实现"><span class="nav-number">3.</span> <span class="nav-text">游戏功能实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#穿墙效果"><span class="nav-number">3.1.</span> <span class="nav-text">穿墙效果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#蛇的身子变长（重点）"><span class="nav-number">3.2.</span> <span class="nav-text">蛇的身子变长（重点）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#碰撞检测"><span class="nav-number">3.3.</span> <span class="nav-text">碰撞检测</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#检测吃食物"><span class="nav-number">3.4.</span> <span class="nav-text">检测吃食物</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#计分系统"><span class="nav-number">3.5.</span> <span class="nav-text">计分系统</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Roderick Xiang</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">7</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/roderickxiang" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;roderickxiang" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Roderick Xiang</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.2
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  













<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
